Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
Does a "with" statement support type hinting?

Can you define the type hint for a variable defined with the with syntax?

with example() as x:
    print(x)

I would like to type hint the above to say that x is a str (as an example).

The only work around that I've found is to use an intermediate variable, but this feels hacky.

with example() as x:
    y: str = x
    print(y)

I can't find an example in the typing documentation.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Usually type annotations are placed at the API boundaries. In this case the type should be inferred from example.__enter__. In case that function doesn't declare any types, the solution is to create a corresponding stub file in order to help the type checker infer that type.

Specifically this means creating a .pyi file with the same stem as the module from which Example was imported. Then the following code can be added:

class Example:
    def __enter__(self) -> str: ...
    def __exit__(self, exc_type, exc_value, exc_traceback) -> None: ...
over 4 years ago · Santiago Trujillo Denunciar

0

PEP 526, which has been implemented in Python 3.6, allows you to annotate variables. You can use, for example,

x: str
with example() as x:
    [...]

or

with example() as x:
    x: str
    [...]
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda